Type Conversion


Type conversion is the process of converting data from one type to another. JavaScript performs type conversion in two ways: implicitly (automatic) and explicitly (manual).

Implicit Conversion

JavaScript automatically converts data types when necessary. This is known as implicit conversion or type coercion.

console.log("5" - 3); // 2 (string "5" is converted to number 5)
console.log("5" + 3); // "53" (number 3 is converted to string "3")

Explicit Conversion

Explicit conversion is when you manually convert data from one type to another using built-in methods.

1. String to Number

let num = Number("123"); // 123
let floatNum = parseFloat("3.14"); // 3.14
let intNum = parseInt("42"); // 42

2. Number to String

let str = String(123); // "123"
let str2 = (456).toString(); // "456"

3. Boolean Conversion

let bool1 = Boolean(1); // true
let bool2 = Boolean(0); // false
let bool3 = Boolean("hello"); // true
let bool4 = Boolean(""); // false

Examples

Here are some examples of type conversion in JavaScript:

console.log(Number("123")); // 123
console.log(String(123)); // "123"
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hello")); // true

For more detailed information, you can check out resources like W3Schools and JavaScript.info.